<script setup lang='ts'>
import { computed, ref } from 'vue';

const username = ref('张三')
type ToyItem = { id: number, name: string, count: number, price: number }
const list = ref<ToyItem[]>([
    {
        id: 1, name: "芭比娃娃", count: 1, price: 288
    },
    {
        id: 2, name: "弹弓", count: 5, price: 2
    },
    {
        id: 3, name: "四驱车", count: 1, price: 5
    },
    {
        id: 4, name: "陀螺", count: 1, price: 10
    }
])
const delToy = (id:number)=>{
    if(confirm('你确定要删除吗?')){
        list.value = list.value.filter(item => item.id !== id)
    }
}
const addToyItem = ()=>{
    let name = prompt('请输入玩具名称')
    let price = +prompt('请输入玩具玩具价格')!
    let count = +prompt('请输入玩具数量')!
    list.value.push({
        name:name!,
        id:Math.max(...list.value.map(item=>item.id))+1,
        price:price,
        count:count
    })    
}
const allPrice = computed(()=>{
    return list.value.reduce((preValue:number,item:ToyItem)=>{
        return preValue + item.count * item.price
    },0)
})
const allCount = computed(()=>{
    return list.value.reduce((preValue:number,item:ToyItem)=>{
        return preValue + item.count
    },0)
})

const userNameComputed = computed({
    get(){
        return username.value
    },
    set(value){
        username.value = value
    }
})
</script>

<template>
    <div class="container">
        <h1>小黑的礼物清单<Button @click="addToyItem">添加礼物</Button></h1>
        <table border="2">
            <thead>
                <th>玩具名称 </th>
                <th>玩具数量</th>
                <th>玩具价格</th>
                <th>操作</th>
            </thead>
            <tbody>
                <tr v-for="item in list" :key="item.id">
                    <td align="center" width="200">{{ item.name }}</td>
                    <td align="center" width="100">{{ item.count }}</td>
                    <td align="center" width="100">{{ item.price }}</td>
                    <td align="center" width="100"><a @click.prevent = 'delToy(item.id)'>删除</a></td>
                </tr>
            </tbody>
        </table>
        <p>
            当前总数量为：{{ allCount }} 当前总价格为：{{ allPrice }}
        </p>
        <p>{{ username }}</p>
        <p><input type="text" v-model="username"></p>
        <p>{{ userNameComputed }}</p>
        <p><input type="text" v-model="userNameComputed"></p>
    </div>
</template>

<style scoped></style>